<template>
	<d2-container>
		<template slot="header">
			<el-form class="header-area" ref="indexForm" :model="indexForm" label-width="88px" style="height: auto">
				<el-row>
					<el-col :span="4" v-if="shopId == 0">
						<el-form-item label="选择门店" prop="shopId">
							<el-select v-model="indexForm.shopId" placeholder="请选择" style="width: 100%;">
								<el-option value="0" label="请选择">请选择</el-option>
								<el-option value="10" label="科德店">科德店</el-option>
								<el-option value="11" label="江南万达店">江南万达店</el-option>
								<el-option value="12" label="秀灵店">秀灵店</el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="5">
						<el-form-item label="汇总方式" prop="groupBy">
							<el-checkbox-group v-model="indexForm.groupBy" @change="chooseGroupBy">
								<el-checkbox label="channelType" border>按渠道</el-checkbox>
								<el-checkbox label="payType" border>按支付方式</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-col>
					<el-col :span="4" v-if="isShowPayOption">
						<el-form-item label="支付方式" prop="payType">
							<el-select v-model="indexForm.payType" placeholder="请选择" style="width: 100%;">
								<el-option label="全部" value=""></el-option>
								<el-option label="账户支付" value="1"></el-option>
								<el-option label="现金支付" value="2"></el-option>
								<el-option label="通联支付" value="3"></el-option>
                <el-option label="支付宝记账" value="4"></el-option>
								<el-option label="微信记账" value="5"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="选择时间" prop="time">
							<el-date-picker
								v-model="indexForm.time"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="timestamp"
								align="right"
								:default-time="['00:00:00', '23:59:59']"
								@change="chooseDay"
								style="width: 100%"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<div class="search-submit">
							<el-button type="primary" size="medium" loading v-if="loading">查询</el-button>
							<el-button type="primary" size="medium" @click="submitForm('indexForm')" v-else>查询</el-button>

							<el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<template>
			<el-table :data="tableData" stripe border show-summary :summary-method="getSummaries" style="width: 100%">
				<el-table-column type="index" fixed label="序号" width="50"></el-table-column>
				<el-table-column prop="incomeDay" label="营收日期"></el-table-column>

				<el-table-column prop="channelType" label="订单渠道" v-if="isShowChannel">
					<template slot-scope="scope">
						<template v-if="scope.row.channelType == 1">
							门店订单
						</template>
						<template v-if="scope.row.channelType == 2">
							美团订单
						</template>
						<template v-if="scope.row.channelType == 3">
							抖音订单
						</template>
					</template>
				</el-table-column>

				<el-table-column prop="payType" label="支付方式" v-if="isShowPay">
					<template slot-scope="scope">
						<template v-if="scope.row.payType == 3">
							通联支付
						</template>
						<template v-else-if="scope.row.payType == 2">
							现金支付
						</template>
						<template v-else-if="scope.row.payType == 1">
							账户支付
						</template>
						<template v-else>
							全部
						</template>
					</template>
				</el-table-column>

				<el-table-column prop="orderCount" label="付款订单数"></el-table-column>
				<el-table-column prop="orderAmount" label="订单金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="payableAmount" label="应收金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="incomeAmount" label="总营收(核销+实付-退款-找零)" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="thirdPaidAmount" label="第三方核销金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="shopIncomeAmount" label="实收(实付-退款-找零)" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="payAmount" label="用户实付金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="refundAmount" label="店铺退款金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="changeAmount" label="店铺找零金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="reduceAmount" label="减免金额" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="giftAmount" label="赠送金额" :formatter="moneyFilter"></el-table-column>
			</el-table>
		</template>
	</d2-container>
</template>
<script>
import { findEverydayRevenueList } from '@api/restaurant/tempReport'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
export default {
  name: 'tempReport-everydayRevenue',
  data () {
    return {
      indexForm: {
        shopId: '0',
        payType: '',
        time: [dayjs().startOf('month'), dayjs().endOf('month')],
        groupBy: []
      },

      startTime: dayjs()
        .startOf('month')
        .format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs()
        .endOf('month')
        .format('YYYY-MM-DD HH:mm:ss'),

      tableData: [],
      isShowChannel: false,
      isShowPay: false,
      isShowPayOption: false,
      loading: false
    }
  },
  computed: {
    ...mapState('d2admin/permission', ['shopId'])
  },

  mounted () {
    this.indexForm.shopId = this.shopId == 0 ? '10' : this.shopId.toString()
    this.fetchData()
  },
  methods: {
    fetchData () {
      if (this.loading) {
        return
      }
      this.loading = true
      let str = this.indexForm.groupBy.toString()
      if (str.indexOf('payType') > -1) {
        this.isShowPay = true
      } else {
        this.isShowPay = false
      }
      if (str.indexOf('channelType') > -1) {
        this.isShowChannel = true
      } else {
        this.isShowChannel = false
      }

      findEverydayRevenueList({
        shopId: this.indexForm.shopId,
        payType: this.isShowPay ? this.indexForm.payType : '',
        // groupBy: this.isShowChannel ? this.indexForm.groupBy.toString() : '',
        groupBy: this.indexForm.groupBy.toString(),
        startTime: this.startTime,
        endTime: this.endTime
      })
        .then(res => {
          this.tableData = res.data

          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    getSummaries (param) {
      // 表格小计
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '小计'
          return
        }

        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          // 需要判断列表显示渠道、支付方式
          if (!this.isShowChannel && !this.isShowPay) {
            if (index == 2) {
              // 数量
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
            } else if (index != 0 && index != 1 && index != 2) {
              // 金额
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] = Number(sums[index]).toFixed(2)
            } else {
              sums[index] = ''
            }
          } else if ((this.isShowChannel && !this.isShowPay) || (!this.isShowChannel && this.isShowPay)) {
            if (index == 3) {
              // 数量
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
            } else if (index != 0 && index != 1 && index != 2 && index != 3) {
              // 金额
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] = Number(sums[index]).toFixed(2)
            } else {
              sums[index] = ''
            }
          } else if (this.isShowChannel && this.isShowPay) {
            if (index == 4) {
              // 数量
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
            } else if (index != 0 && index != 1 && index != 2 && index != 3 && index != 4) {
              // 金额
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] = Number(sums[index]).toFixed(2)
            } else {
              sums[index] = ''
            }
          }
        }
      })

      return sums
    },
    moneyFilter (row, column, cellValue, index) {
      let value = cellValue
      if (value == '' || value == null || value == undefined) {
        return '0.00'
      } else if (value == 0) {
        return '0.00'
      } else {
        let newVal = parseFloat(value)
        if (newVal < 0) {
          value = (-1 * parseFloat((value + '').replace(/[^\d\.-]/g, ''))).toFixed(2) + ''
        } else {
          value = parseFloat((value + '').replace(/[^\d\.-]/g, '')).toFixed(2) + ''
        }

        let left = value
          .split('.')[0]
          .split('')
          .reverse()
        let right = value.split('.')[1]

        let t = ''
        for (let i = 0; i < left.length; i++) {
          t += left[i] + ((i + 1) % 3 === 0 && i + 1 !== left.length ? ',' : '')
        }

        if (newVal < 0) {
          return (
            '-' +
						t
						  .split('')
						  .reverse()
						  .join('') +
						'.' +
						right
          )
        } else {
          return (
            t
              .split('')
              .reverse()
              .join('') +
						'.' +
						right
          )
        }
      }
    },

    chooseDay (val) {
      this.startTime = dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss')
      this.endTime = dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss')
    },
    chooseGroupBy (val) {
      let str = val.toString()
      if (str.indexOf('payType') > -1) {
        this.isShowPayOption = true
      } else {
        this.isShowPayOption = false
      }
    },

    submitForm (formName) {
      this.fetchData()
    },
    resetForm () {
      // this.$refs[formName].resetFields()
      this.indexForm.shopId = this.shopId == 0 ? '10' : this.shopId.toString()
      this.indexForm.payType = ''
      this.indexForm.groupBy = []

      this.indexForm.time = [dayjs().startOf('month'), dayjs().endOf('month')]
      this.startTime = dayjs()
        .startOf('month')
        .format('YYYY-MM-DD HH:mm:ss')
      this.endTime = dayjs()
        .endOf('month')
        .format('YYYY-MM-DD HH:mm:ss')

      this.fetchData()
    }
  }
}
</script>

<style lang="scss" scoped>
// 样式请务必加scoped
.el-checkbox-group {
	.el-checkbox {
		margin-right: 0;
	}
}
</style>
